/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.health.ecology.fa.central.client;

import com.huawei.health.ecology.fa.central.module.CentralClientModule;
import com.huawei.health.ecology.fa.central.operator.CentralOperationCode;
import com.huawei.health.ecology.fa.utils.LogUtil;
import com.huawei.healthecology.data.platform.PlatformRequest;
import com.huawei.healthecology.json.JsonMapperType;
import com.huawei.healthecology.operator.JsRemoteOperator;

import lombok.Builder;
import ohos.ace.ability.AceInternalAbility;
import ohos.rpc.MessageOption;
import ohos.rpc.MessageParcel;

import java.util.Optional;

/**
 * The central client for Js Fa
 */
public class CentralJsClient extends AceInternalAbility {
    private static final String TAG = "CentralJsClient";

    private static final String BUNDLE_NAME = "com.huawei.health.ecology.fa";

    private static final String ABILITY_NAME = "com.huawei.health.ecology.fa.central.client.CentralJsClient";

    /**
     * The builder constructor for CentralJsClient
     *
     * @param mapperType The mapper type
     */
    @Builder
    public CentralJsClient(JsonMapperType mapperType) {
        super(BUNDLE_NAME, ABILITY_NAME);
        setInternalAbilityHandler(this::onProcessRequest);
        Optional.ofNullable(mapperType).ifPresent(CentralClientModule::configJsonMapper);
    }

    private boolean onProcessRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
        LogUtil.debug(TAG, "onProcessRequest code:" + code);
        return CentralOperationCode.processJsFaOperation(
            JsRemoteOperator.of(data.readRemoteObject(), reply),
            PlatformRequest.builder()
                .requestCode(code)
                .requestValue(data.readString())
                .build());
    }
}
